#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: jenkins_package.py 
@version:
@time: 2022/04/02 
"""
from datetime import datetime

from TapClientCore.mongo_for_api import MongoForApi
from TapDevops.CI.tapjenkins.dev_jenkins import DevJenkins
from TapUtil.Tfeishu.feishuReport.report_package import ReportPackage

mongodb_setting = {'host': '36.134.131.197', 'port': '27029', 'db': 'tapclient-v3', 'user': '', 'password': ''}
MFA = MongoForApi(mongodb_setting)


class JenkinsPackage(DevJenkins, ReportPackage):
    TapDevopsCollection = 'TapDevops'
    BuildRecordCollection = 'BuildRecord'

    def jenkins_package_time_task(self):
        """
        IN_PROGRESS
        FAILED
        ABORTED
        SUCCESS
        """
        result = None
        in_progress = []
        for_failed = []
        filter = {
            'useage': 'package',
            'project': self.project_name,
        }
        result = MFA.query(self.TapDevopsCollection, filter)
        if result:
            result = result[0]
            in_progress = result.get("in_progress")
            for_failed = result.get("for_failed")
        else:
            MFA.insert_one(
                self.TapDevopsCollection,
                {
                    **filter,
                    'in_progress': [],
                    'for_failed': [],
                }
            )
        last = self.get_build_useful_info()[:10]
        # start
        for one in last:
            this_status = one.get('status')
            this_stages = one.get('stages')
            this_build_number = one.get('build_number')
            if this_status == 'IN_PROGRESS':
                if this_stages:
                    if this_build_number in in_progress:
                        pass
                    else:
                        if not MFA.query(
                                self.BuildRecordCollection,
                                {
                                    'build_number': this_build_number
                                }
                        ):
                            one['start_time'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                            MFA.insert_one(
                                self.BuildRecordCollection,
                                one
                            )
                        if len(this_stages) >= 2:
                            one['end_time'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                            MFA.update(
                                self.BuildRecordCollection,
                                {'build_number': this_build_number},
                                {"$set": one}
                            )
                            in_progress.append(this_build_number)
                            for_failed.append(this_build_number)
                            self.start_jenkins_feishu(one)
        MFA.update(
            self.TapDevopsCollection,
            filter,
            {
                '$set': {
                    'in_progress': in_progress
                }
            }
        )
        MFA.close()
        # finish
        for one in last:
            this_build_number = one.get('build_number')
            if this_build_number in in_progress:
                this_status = one.get('status')
                if this_status == 'IN_PROGRESS':
                    pass
                elif this_status == 'SUCCESS':
                    if not MFA.query(
                            self.BuildRecordCollection,
                            {'build_number': this_build_number}
                    ):
                        one['end_time'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                        MFA.insert_one(
                            self.BuildRecordCollection,
                            one
                        )
                    else:
                        one['end_time'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                        MFA.update(
                            self.BuildRecordCollection,
                            {'build_number': this_build_number},
                            {"$set": one}
                        )
                    self.finish_jenkins_feishu(one)
                    in_progress.pop(in_progress.index(this_build_number))
                    for_failed.pop(for_failed.index(this_build_number))
        MFA.update(
            self.TapDevopsCollection,
            filter,
            {
                '$set': {
                    'in_progress': in_progress
                }
            }
        )
        MFA.update(
            self.TapDevopsCollection,
            filter,
            {
                '$set': {
                    'for_failed': for_failed
                }
            }
        )
        MFA.close()
        # failed
        for one in last:
            this_status = one.get('status')
            this_stages = one.get('stages')
            this_build_number = one.get('build_number')
            if this_status in ['FAILED', 'ABORTED']:
                if this_build_number in in_progress:
                    if not MFA.query(
                            self.BuildRecordCollection,
                            {'build_number': this_build_number}
                    ):
                        one['end_time'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                        MFA.insert_one(
                            self.BuildRecordCollection,
                            one
                        )
                    else:
                        one['end_time'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                        MFA.update(
                            self.BuildRecordCollection,
                            {'build_number': this_build_number},
                            {"$set": one}
                        )
                    self.failed_jenkins_feishu(one)
                    in_progress.pop(in_progress.index(this_build_number))
                    for_failed.pop(for_failed.index(this_build_number))
        MFA.update(
            self.TapDevopsCollection,
            filter,
            {
                '$set': {
                    'in_progress': in_progress
                }
            }
        )
        MFA.update(
            self.TapDevopsCollection,
            filter,
            {
                '$set': {
                    'for_failed': for_failed
                }
            }
        )
        MFA.close()

    def start_jenkins_feishu(self, info):
        print(info)
        build_number = info.get('build_number')
        commit = self.get_commit_info(build_number)
        print(f'start {build_number}')
        branch_par = self.get_build_branch_info(build_number)
        info["change_list"] = commit
        info["branch_par"] = branch_par
        self.template_edit_start(info)
        self.report()

    def finish_jenkins_feishu(self, info):
        build_number = info.get('build_number')
        print(f'finish {build_number}')
        commit = self.get_commit_info(build_number)
        branch_par = self.get_build_branch_info(build_number)
        info["change_list"] = commit
        info["branch_par"] = branch_par
        self.template_edit_finish(info)
        self.report()

    def failed_jenkins_feishu(self, info):
        self.template_edit_finish(info)
        self.report()
